package ch03.cjlibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author Jane
 * @date 2024-03-25 17:16
 */

public class CglibInterceptorFactory {
    public static <T>T getInstance(Class<T> target){
        Enhancer enhancer =new Enhancer();
        //enhancer.setCallback(new BuyInterceptor());

        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

                Object res = null;
                try {
                    String name = method.getName();
                   // System.out.println(name);

                    if (name.startsWith("pay")){
                        before();
                        res = methodProxy.invokeSuper(o, args);
                        System.out.println(res);
                        after();
                    }else{
                        res = methodProxy.invokeSuper(o, args);
                        System.out.println(res);
                    }


                } catch (Throwable e) {
                    e.printStackTrace();
                    back();
                }

                return res;
            }
        });
        enhancer.setSuperclass(target);//指定要继承的父类的类型,也就是目标代理对象
        return (T) enhancer.create();
    }

    public static void before(){
        System.out.println("开启事务");
    }
    public static void back(){
        System.out.println("回滚事务");
    }
    public static void after(){
        System.out.println("提交事务");
    }
}
